package com.hichao.cs.thrift.front;

import java.util.Arrays;
import java.util.Map;

import org.apache.thrift.TException;

import redis.clients.jedis.Jedis;

import com.hichao.cs.helper.CSHelper;
import com.hichao.cs.thrift.front.FrontService.Iface;

public class FrontServiceImpl implements Iface, CSHelper {

	private String redisHost = "192.168.1.62";
	private int redisPort = 6379;
	
	@Override
	public void SendMessage(String source, String target, String text) {
		logger.info(source + " send " + target + " : " + text);
		String key = "com.hichao.cs.chat.pull." + "from." + source + ".to." + target;
		logger.info("key: {}", key);
		logger.info("save message to redis: {}", text);
		String field = "" + System.currentTimeMillis();
		logger.info(field);
		Jedis jedis = new Jedis(this.redisHost, this.redisPort);
		jedis.hset(key, field, text);
		Map<String, String> strStrMap = jedis.hgetAll(key);
		if (!strStrMap.isEmpty()) {
			String[] tmp = new String[strStrMap.size()];
			String[] subKeyArray = strStrMap.keySet().toArray(tmp);
			Arrays.sort(subKeyArray);
			final int N = 10;
			if (subKeyArray.length > N){
				String[] delSubKeyArray = new String[subKeyArray.length - N];
				System.arraycopy(subKeyArray, 0, delSubKeyArray, 0, subKeyArray.length - N);
				jedis.hdel(key, delSubKeyArray);
			}
		}
		strStrMap = jedis.hgetAll(key);
		logger.info("pushself {} ", strStrMap);
		jedis.close();
	}

	@Override
	public void SendFile(String source, String target, String url)
			throws TException {
		logger.info(source + " send " + target + " : " + url);
	}
}
